package RunningTask

import (
	"awesomeTask/system/kernel"
	exec2 "os/exec"
	"sync"
)

type RunTaskProcess struct {
	TaskLogId int64
	TaskId    string
	Stdout    *kernel.StdWriter
	Stderr    *kernel.StdWriter
	Cmd       *exec2.Cmd
	StartAt   int64
}
type RunningTask struct {
	runningTask sync.Map
	pushChan    chan RunTaskProcess
	endChan     chan RunTaskProcess
}

func (RunningTask *RunningTask) PushRunningTask(process RunTaskProcess) {
	RunningTask.pushChan <- process
}
func (RunningTask *RunningTask) EndTask(process RunTaskProcess) {
	RunningTask.endChan <- process
}

func (RunningTask *RunningTask) HandleBack() {
	var process RunTaskProcess
	select {
	case process = <-RunningTask.pushChan:
		if data, ok := RunningTask.runningTask.Load(process.TaskId); ok {
			runningMap := data.(map[int64]RunTaskProcess)
			runningMap[process.TaskLogId] = process
			RunningTask.runningTask.Store(process.TaskId, runningMap)
		} else {
			runningMap := make(map[int64]RunTaskProcess)
			runningMap[process.TaskLogId] = process
			RunningTask.runningTask.Store(process.TaskId, runningMap)
		}
		break
	case process = <-RunningTask.endChan:
		if data, ok := RunningTask.runningTask.Load(process.TaskId); ok {
			runningMap := data.(map[int64]RunTaskProcess)
			delete(runningMap, process.TaskLogId)
			RunningTask.runningTask.Store(process.TaskId, runningMap)
		}
		break
	}
}
